package api

import (
	"apps/cqrs-example/internal/products/features/creating_product/commands"
	dtos3 "apps/cqrs-example/internal/products/features/creating_product/dtos"
	"net/http"

	"github.com/go-playground/validator"
	"github.com/labstack/echo/v4"
	"github.com/mehdihadeli/go-mediatr"
)

type ProductsController struct {
	echo      *echo.Echo
	validator *validator.Validate
}

func NewProductsController(echo *echo.Echo) *ProductsController {
	return &ProductsController{
		echo:      echo,
		validator: validator.New(),
	}
}

func (pc *ProductsController) createProduct() echo.HandlerFunc {
	return func(ctx echo.Context) error {
		request := &dtos3.CreateProductRequestDto{}
		if err := ctx.Bind(request); err != nil {
			return err
		}

		if err := pc.validator.StructCtx(ctx.Request().Context(), request); err != nil {
			return err
		}

		command := commands.NewCreateProductCommand(request.Name, request.Description, request.Price)
		result, err := mediatr.Send[*commands.CreateProductCommand, *dtos3.CreateProductCommandResponse](ctx.Request().Context(), command)
		if err != nil {
			return err
		}

		return ctx.JSON(http.StatusCreated, result)
	}
}
